package com.universal.base.resp;

import com.universal.common.enums.ErrorCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ApiResult<T> implements Serializable {

    private String state;
    private String msg;
    private String errorCode;
    private T result;
    private static String SUCCESS_CODE = "1";
    private static String FAIL_CODE = "0";

    public static ApiResult success() {
        ApiResult apiResult = new ApiResult();
        apiResult.setState(SUCCESS_CODE);
        return apiResult;
    }

    public static <T> ApiResult success(T data) {
        ApiResult apiResult = new ApiResult();
        apiResult.setState(SUCCESS_CODE);
        apiResult.setResult(data);
        return apiResult;
    }

    public static <T> ApiResult success(T data, String note) {
        ApiResult apiResult = new ApiResult();
        apiResult.setState(SUCCESS_CODE);
        apiResult.setResult(data);
        apiResult.setMsg(note);
        return apiResult;
    }

    public static <T> ApiResult failure() {
        ApiResult apiResult = new ApiResult();
        apiResult.setState(FAIL_CODE);
        return apiResult;
    }

    public static <T> ApiResult failure(String note) {
        ApiResult apiResult = new ApiResult();
        apiResult.setState(FAIL_CODE);
        apiResult.setMsg(note);
        return apiResult;
    }

    public static <T> ApiResult failure(String note, String errorCode) {
        ApiResult apiResult = new ApiResult();
        apiResult.setState(FAIL_CODE);
        apiResult.setMsg(note);
        apiResult.setErrorCode(errorCode);
        return apiResult;
    }

    public static <T> ApiResult failure(String note, T data, String errorCode) {
        ApiResult apiResult = new ApiResult();
        apiResult.setState(FAIL_CODE);
        apiResult.setMsg(note);
        apiResult.setResult(data);
        apiResult.setErrorCode(errorCode);
        return apiResult;
    }

    public static <T> ApiResult failure(ErrorCode errorCode) {
        ApiResult apiResult = new ApiResult();
        apiResult.setState(FAIL_CODE);
        apiResult.setMsg(errorCode.getDescription());
        apiResult.setErrorCode(errorCode.getCode());
        return apiResult;
    }

    public static <T> ApiResult failure(ErrorCode errorCode, ApiErrorResult result) {
        ApiResult apiResult = new ApiResult();
        apiResult.setState(FAIL_CODE);
        apiResult.setMsg(errorCode.getDescription());
        apiResult.setErrorCode(errorCode.getCode());
        result.setOutputType(StringUtils.isBlank(result.getOutputType()) ? errorCode.getOutputType() : result.getOutputType());
        apiResult.setResult(result);
        return apiResult;
    }

    public boolean stateSuccess() {
        return SUCCESS_CODE.equals(this.state);
    }
}
